//package com.pengzy.core.gateway_security;
//
//import com.pengzy.comment.core.enums.PrErrorEnum;
//import com.pengzy.comment.core.enums.SecurityEnum;
//import com.pengzy.comment.core.jwt.JwtUtil;
//import com.pengzy.comment.web.exception.CustomException;
//import com.pengzy.comment.web.redis.RedisCache;
//import com.pengzy.comment.web.result.JsonResult;
//import com.pengzy.core.conf.IgnoreUrlsConfig;
//import com.pengzy.supports.dto.LoginUserDetails;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.lang3.StringUtils;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.core.annotation.Order;
//import org.springframework.http.HttpCookie;
//import org.springframework.http.HttpHeaders;
//import org.springframework.security.authentication.*;
//import org.springframework.security.core.context.SecurityContext;
//import org.springframework.security.core.context.SecurityContextImpl;
//import org.springframework.security.core.userdetails.UserDetails;
//import org.springframework.security.web.server.context.ServerSecurityContextRepository;
//import org.springframework.stereotype.Component;
//import org.springframework.util.AntPathMatcher;
//import org.springframework.util.PathMatcher;
//import org.springframework.web.server.ServerWebExchange;
//import reactor.core.publisher.Mono;
//
//import javax.annotation.Resource;
//import javax.security.sasl.AuthenticationException;
//import java.util.List;
//import java.util.Objects;
//import java.util.concurrent.TimeUnit;
//
///**
// * @author xiaozhi 2023/7/17
// */
//
//@Slf4j
//@Component
//public class JwtSecurityContextRepository implements ServerSecurityContextRepository {
//
//    private UserService userService;
//
//    @Autowired
//    IgnoreUrlsConfig ignoreUrlsConfig;
//
//    @Autowired
//    private RedisCache redisCache;
//
//
//    private  final String TOKEN="token";
//
//    public JwtSecurityContextRepository(UserService userService){
//        this.userService = userService;
//    }
//
//
//    @Override
//    public Mono<Void> save(ServerWebExchange exchange, SecurityContext context) {
//        return Mono.empty();
//    }
//
//    @Override
//    public Mono<SecurityContext> load(ServerWebExchange exchange){
//        String path = exchange.getRequest().getPath().toString();
//        log.info("加载token:JwtSecurityContextRepository：PATH:{}",path);
//        List<String> ignoreUrls = ignoreUrlsConfig.getUrls();
//        // 过滤路径
//        PathMatcher pathMatcher = new AntPathMatcher();
//        for (String ignoreUrl : ignoreUrls) {
//            if (pathMatcher.match(ignoreUrl,path)) {
//                return Mono.empty();
//            }
//        }
//        //获取请求中的token字符串
//        String token = exchange.getRequest().getHeaders().getFirst(TOKEN);
//        if (StringUtils.isNotBlank(token)){
//            try {
//                //token能正常解析，该用户登录过，现在只需验证登录是否过期即可
//                String userid = JwtUtil.parseJWTKey(token);
//                //从redis中获取用户信息
//                String redisKey = SecurityEnum.LOGIN_KEY.getValue() + userid;
//                LoginUserDetails loginUser = redisCache.getCacheObject(redisKey);
//                if(Objects.isNull(loginUser)){
//                    //throw new CustomException(PrErrorEnum.ERROR_1002.getInfo(),PrErrorEnum.ERROR_1002.getCode());
//                    return Mono.error(new CustomException(PrErrorEnum.ERROR_1002.getInfo(),PrErrorEnum.ERROR_1002.getCode()));
//                }
//                // TODO: 2023/2/25 续期
//                redisCache.expire(SecurityEnum.LOGIN_KEY.getValue()+userid,24, TimeUnit.HOURS);
//                Mono<UserDetails> userDetailsMono = userService.findByUsernameWithSom(loginUser);
//                Mono<SecurityContext> mono = userDetailsMono.map(s -> {
//                    UsernamePasswordAuthenticationToken t = new UsernamePasswordAuthenticationToken(s.getUsername(), null, s.getAuthorities());//验证用户不再填入密码
//                    SecurityContextImpl data = new SecurityContextImpl();
//                    data.setAuthentication(t);
//                    return data;
//                });
//                return mono;
//            }catch (AccountExpiredException e){
//                //return Mono.error(new AccountExpiredException("登录用户已过期"));
//                //throw new AccountExpiredException("登录用户已过期");
//                return Mono.error(new AccountExpiredException( "找不到身份凭据"));
//            }catch (Exception e){
//                //return Mono.error(new CustomException("token不能正常解析"));
//                //throw new CustomException("token不能正常解析");
//                return Mono.error(new CustomException( "token不能正常解析"));
//            }
//        }else {
//            //throw new CustomException("请求头的TOKEN参数为空");
//            return Mono.error(new AuthenticationException("请求头的TOKEN参数为空"));
//        }
//    }
//}
